<script setup>
import {computed, defineEmits, defineProps, onMounted, ref, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {formatDate, getRangeDays} from '@/utils/index.js';
import {showToast} from 'vant';
import {isTimePassed} from '@/utils/time.js';
import api from '@/api/index.js';
import moment from 'moment';
import {billTypeEnum} from '@/views/activityPages/const/billType.ts';
import {getToken} from "@/utils/user.js";

const router = useRouter();
const route = useRoute();
console.log('route', route.params)
const emit = defineEmits(['closePopup']);
const props = defineProps({
  showPopup: Boolean,
  sessionlist: Object,
  scenicId: String,
  sortid: String,
  title: String,
  marketPrice: Number,
  productid: String,
  buyLimitCountvalue: Number,
  kindsId: String,
  goodsInfoList: Array,
  spotId: String,
  deposit: Number
});

const maxvalue = ref(props.buyLimitCountvalue);
const productName = ref(route.params.name);

const number = ref(1);

const price = ref(props.marketPrice + (props.deposit || 0));
const allPrice = ref(price.value);
const showTime = ref(false);

const minDate = ref(null);
const maxDate = ref(null);

const loading = ref(true);
const ticket = ref({});
const getTicketDetail = () => {
  const params = {
    id: ticketTypes.value,
    kindsId: props.kindsId,
  };
  loading.value = true;
  api
      .getScenicSpotid(params)
      .then((res) => {
        ticket.value[params.id] = res.data.goodsInfoVo;
        const {validStartTime, validEndTime} = res.data.goodsInfoVo;
        if (validStartTime) {
          minDate.value = new Date(validStartTime);
          maxDate.value = new Date(validEndTime);
        } else {
          const currentDate = new Date();
          minDate.value = currentDate;
          const tenDaysLater = new Date(currentDate);
          tenDaysLater.setDate(currentDate.getDate() + 30);
          maxDate.value = tenDaysLater;
          // 设置共享预约开始时间，共享预约结束时间
          const subscribeLater = new Date(currentDate);
          subscribeLater.setDate(currentDate.getDate() + 3);
          subscribeMinDate.value = currentDate;
          subscribeMaxDate.value = subscribeLater;

          subscribeCurrentTime.value = moment().add(1, 'minutes').format('HH:mm').split(':');
          endSubscribeCurrentTime.value = moment().add(61, 'minutes').format('HH:mm').split(':');
        }
        var {list, more} = getRangeDays(minDate.value, maxDate.value);
        if (productName.value == 2) {
          var gr = getRangeDays(new Date(), moment().add(3, 'days').toDate());
          list = gr.list.slice(0, 3);
          more = gr.more;

        }
        timeList.value = list ?? [];
        console.log('timeList.value1111', JSON.stringify(timeList.value))
        if (props.sessionlist.length) {
          const allIsTimePassed = props.sessionlist.every(
              (item) => item.isTimePassed
          );
          timeList.value.forEach((item) => {
            if (item.name === '今天' && allIsTimePassed) {
              item.disabled = true;
            }
          });
          if (timeList.value[0]?.disabled) {
            // timeKey.value = timeList.value[1]?.yearTime;
            session.value = props.sessionlist[0].id;
          } else {
            // timeKey.value = timeList.value[0]?.yearTime;
          }
        } else {
          // timeKey.value = timeList.value[0]?.yearTime;
        }

        timeKey.value = timeList.value.filter((item) => !isDateDisabled(item.yearTime))?.[0]?.yearTime

        timeShowMore.value = more;
      })
      .finally(() => {
        loading.value = false;
      });
};

const numberChange = (e) => {
  if (e === props.buyLimitCountvalue) {
    showToast(`限购${maxvalue.value}张`);
  }
  allPrice.value = (price.value * 10000 * e) / 10000;
};

const overlimit = (e) => {
  if (e === 'plus') {
    if (stepperMax.value === number.value) {
      if (props.sessionlist.length) {
        if (stockCount.value < maxvalue.value) {
          showToast(`库存仅${stockCount.value}张`);
          return;
        }
      }
      showToast(`限购${maxvalue.value}张`);
    }
  }
};

// 设置选中的次卡月卡天卡状态
const checkCard = ref('0');

// 返回会议室今天明天
const getMeetingRoomDate = (index) => {
  if (index === 0) {
    return '今天';
  } else if (index === 1) {
    return '明天';
  } else if (index === 2) {
    return '后天';
  }
  return '';
};

// 切换会议室小时
const meetingRoomTimeChangeClick = (data) => {
  if (checkMeetingRoomHourList.value !== data) {
    checkMeetingRoomHourList.value = data;
    meetingRoomchecked.value = [];
  }
};

const ticketTypes = ref('');
const ticketTypesClick = (item) => {
  if (item.billingMethod) {
    checkCard.value = item.billingMethod;
  }
  if (productName.value === '2' && [1, 2].includes(item.billingMethod)) {
    api.getHourPeriod(props.spotId).then((res) => {
      res.data.sort((a, b) => new Date(a.spotDate) - new Date(b.spotDate));
      meetingRoomHourList.value = res.data;
      checkMeetingRoomHourList.value = res.data[0].spotDate;
    });
  } else {
    meetingRoomchecked.value = [];
  }
  if (item.buyType) {
    maxvalue.value = item.buyLimitCount;
  } else {
    maxvalue.value = 99;
  }
  price.value = item.marketPrice;
  ticketTypes.value = item.id;
  allPrice.value = (item.marketPrice * 10000 * number.value) / 10000;

  console.log('checkCard.value5566', checkCard.value)
  console.log('item', JSON.stringify(item))
  //   getTicketDetail()
};

const stockCount = ref(0);
const sessionClick = (item) => {
  if (item.isTimePassed && isToday.value) {
    return;
  }
  stockCount.value = item.stockCount;
  session.value = item.id;
};

const stepperMax = computed(() => {
  if (props.sessionlist.length) {
    if (stockCount.value < maxvalue.value) {
      return stockCount.value;
    }
  }
  return maxvalue.value;
});

watch(stepperMax, () => {
  if (!stepperMax.value) {
    number.value = 0;
  }
});

const timeList = ref([]);
const timeKey = ref('');
const timeKeyDate = computed(() => new Date(timeKey.value)); // 将日期字符串转换为日期对象

const isToday = computed(() => {
  const temp = timeList.value.find((item) => item?.yearTime === timeKey.value);
  return temp?.name === '今天';
});

const timeShowMore = ref(true);
const selectChange = (data) => {
  const time = formatDate(data);
  time.yearTime = time.yearTime.replaceAll('-', '/')
  console.log('selectChange time', time)
  console.log('timeList.value ', timeList.value)
  const repeat = timeList.value.some((item) => {
    return item.yearTime === time.yearTime;
  });
  if (!repeat) {
    const len = timeList.value?.length;
    timeList.value[len - 1] = time;
  }
  timeKey.value = time.yearTime;
  showTime.value = false;
};

const bookClick = () => {
  if (!getToken()) {
    router.push('/login')
    return;
  }
  console.log(
      'bookClick productName.value=',
      productName.value,
      'checkCard.value',
      checkCard.value
  );
  // 计费方式 会议室/办公室：1-小时 2-天 3-月 健身房：4-次卡 5-10次卡 6-月卡
  if (productName.value === '活动预约') {
    if (!stepperMax.value) {
      if (!maxvalue.value) {
        showToast('暂无库存');
        return;
      }
    }
    router.push({
      path: '/activityVerifyScenicordel',
      query: {
        dateS: timeKey.value,
        vanum: number.value,
        scenicId: props.scenicId, //景点id
        productid: ticketTypes.value, //商品id
        ticketTypes: props.sortid, //分类id
        sessionid: session.value, //场次id
        numberMax: stepperMax.value,
        productName: productName.value, //区分活动预约与共享预约
        fitnessCurrentTime: fitnessCurrentTime.value, //健身房预约时间
      },
    });
    // }
  } else if (
      productName.value === '1' ||
      productName.value === '2' ||
      productName.value === '3'
  ) {
    if (checkCard.value === 1 && productName.value === '1') {
      // 小时卡
      // const startTime = [];
      if (subscribeCurrentTime.value.length === 0 || subscribeCurrentDate.value.length === 0) {
        showToast('请选择开始时间');
        return;
      }
      if (endSubscribeCurrentTime.value.length === 0) {
        showToast('请选择结束时间');
        return;
      }
      if (workPrice.value === 0 && currentTicketPrice !== 0) {
        showToast('请先选择时间');
        return;
      }
      router.push({
        path: '/activityVerifyScenicordel',
        query: {
          dateS: timeKey.value,
          vanum: number.value,
          scenicId: props.scenicId, //景点id
          productid: ticketTypes.value, //商品id
          ticketTypes: props.sortid, //分类id
          sessionid: session.value, //场次id
          numberMax: stepperMax.value,
          productName: productName.value, //区分活动预约与共享预约
          price: workPrice.value,
          checkCard: checkCard.value,
          fitnessCurrentTime: fitnessCurrentTime.value, //健身房预约时间
          reservationTimeStart: encodeURIComponent(moment(
              `${subscribeCurrentDate.value.join(
                  '-'
              )} ${subscribeCurrentTime.value.join(':')}`
          ).format('YYYY-MM-DD HH:mm:ss')),
          reservationTimeEnd: encodeURIComponent(moment(
              `${endSubscribeCurrentDate.value.join(
                  '-'
              )} ${endSubscribeCurrentTime.value.join(':')}`
          ).format('YYYY-MM-DD HH:mm:ss')),
        },
      });
    } else if (checkCard.value === 2 && productName.value === '2') {
      // 会议室日卡
      console.log('共享预约2', timeKey.value);
      const currentDate = moment();
      const targetDate = moment(timeKey.value, 'YYYY/MM/DD');
      // 计算当前日期与目标日期的天数差异
      const daysDifference = targetDate.diff(currentDate, 'days');
      const isInThreeDays = daysDifference >= 0 && daysDifference < 2;
      //如果差距少于3天，返回
      if (!isInThreeDays) {
        showToast('选择3天之内的时间');
        return;
      }
      const todayDate = moment().format('YYYY/MM/DD');
      const formattedDate = moment(timeKey.value, 'YYYY/MM/DD').format('YYYY-MM-DD');
      let isCheckHoursBoolean = false;
      if (todayDate === timeKey.value) {
        meetingRoomHourList.value.forEach((item) => {
          if (item.spotDate === formattedDate) {
            item.timeRangeVoList.forEach((el) => {
              const startTime = moment(el.timeRange.split('~')[0], 'YYYY-MM-DD HH:mm:ss');
              const isCheckHours = currentDate.isAfter(startTime);
              if (!isCheckHours && el.timeStatue === 2) {
                isCheckHoursBoolean = true;
              }
            })
          }
        })
      } else {
        meetingRoomHourList.value.forEach((item) => {
          if (item.spotDate === formattedDate) {
            item.timeRangeVoList.forEach((el) => {
              if (el.timeStatue === 2) {
                isCheckHoursBoolean = true;
              }
            })
          }
        })
      }
      if (isCheckHoursBoolean) {
        showToast('当天小时段已有人选择，不能再选择一天的会议室');
        return;
      }
      router.push({
        path: '/activityVerifyScenicordel',
        query: {
          dateS: timeKey.value,
          vanum: number.value,
          scenicId: props.scenicId, //景点id
          productid: ticketTypes.value, //商品id
          ticketTypes: props.sortid, //分类id
          sessionid: session.value, //场次id
          numberMax: stepperMax.value,
          productName: productName.value, //区分活动预约与共享预约
          fitnessCurrentTime: fitnessCurrentTime.value, //健身房预约时间
          reservationTimeStart: encodeURIComponent(`${timeKey.value.replaceAll(
              '/',
              '-'
          )} 00:00:00`),
          reservationTimeEnd: encodeURIComponent(`${timeKey.value.replaceAll('/', '-')} 23:59:59`),
        },
      });
    } else if (checkCard.value === 2 && productName.value === '1') {
      console.log('共享预约3', timeKey.value);
      const currentDate = moment();
      const targetDate = moment(timeKey.value);
      // 计算当前日期与目标日期的天数差异
      const daysDifference = targetDate.diff(currentDate, 'days');
      const isInThreeDays = daysDifference >= 0 && daysDifference < 2;
      //如果差距少于3天，返回
      if (!isInThreeDays) {
        showToast('选择3天之内的时间');
        return;
      }
      router.push({
        path: '/activityVerifyScenicordel',
        query: {
          dateS: timeKey.value,
          vanum: number.value,
          scenicId: props.scenicId, //景点id
          productid: ticketTypes.value, //商品id
          ticketTypes: props.sortid, //分类id
          sessionid: session.value, //场次id
          numberMax: stepperMax.value,
          productName: productName.value, //区分活动预约与共享预约
          fitnessCurrentTime: fitnessCurrentTime.value, //健身房预约时间
          reservationTimeStart: encodeURIComponent(`${timeKey.value.replaceAll(
              '/',
              '-'
          )} 00:00:00`),
          reservationTimeEnd: encodeURIComponent(`${timeKey.value.replaceAll('/', '-')} 23:59:59`),
        },
      });
    } else if (checkCard.value === 3) {
      // 月卡
      console.log('共享预约3');
      router.push({
        path: '/activityVerifyScenicordel',
        query: {
          dateS: timeKey.value,
          vanum: number.value,
          scenicId: props.scenicId, //景点id
          productid: ticketTypes.value, //商品id
          ticketTypes: props.sortid, //分类id
          sessionid: session.value, //场次id
          numberMax: stepperMax.value,
          productName: productName.value, //区分活动预约与共享预约
        },
      });
    } else if (checkCard.value === 4) {
      if (!fitnessCurrentTime.value.length) {
        showToast('请先选择开始时间');
        return;
      }
      const currentDate = moment();
      const targetDate = moment(timeKey.value);
      // 计算当前日期与目标日期的天数差异
      const daysDifference = targetDate.diff(currentDate, 'days');
      const isInThreeDays = daysDifference >= 0 && daysDifference < 2;
      //如果差距少于3天，返回
      if (!isInThreeDays) {
        showToast('选择3天之内的时间');
        return;
      }
      var s = moment(`${timeKey.value.replaceAll('/', '-')} ${fitnessCurrentTime.value.join(':')}`)
      router.push({
        path: '/activityVerifyScenicordel',
        query: {
          dateS: timeKey.value,
          vanum: number.value,
          scenicId: props.scenicId, //景点id
          productid: ticketTypes.value, //商品id
          ticketTypes: props.sortid, //分类id
          sessionid: session.value, //场次id
          numberMax: stepperMax.value,
          productName: productName.value, //区分活动预约与共享预约
          fitnessCurrentTime: fitnessCurrentTime.value, //健身房预约时间
          reservationTimeStart: encodeURIComponent(s.format('YYYY-MM-DD HH:mm:ss')),
          reservationTimeEnd: encodeURIComponent(s
              .add(2, 'hours')
              .format('YYYY-MM-DD HH:mm:ss')),
        },
      });
    } else if (checkCard.value === 5 || checkCard.value === 6) {
      router.push({
        path: '/activityVerifyScenicordel',
        query: {
          dateS: timeKey.value,
          vanum: number.value,
          scenicId: props.scenicId, //景点id
          productid: ticketTypes.value, //商品id
          ticketTypes: props.sortid, //分类id
          sessionid: session.value, //场次id
          numberMax: stepperMax.value,
          productName: productName.value, //区分活动预约与共享预约
          billType: billTypeEnum[checkCard.value],
        },
      });
    } else if (checkCard.value === 1 && productName.value === '2') {
      if (!meetingRoomchecked.value?.length) {
        showToast('请先选择预约时间段');
        return;
      }
      router.push({
        path: '/activityVerifyScenicordel',
        query: {
          dateS: timeKey.value,
          vanum: number.value,
          checkCard: checkCard.value,
          scenicId: props.scenicId, //景点id
          productid: ticketTypes.value, //商品id
          ticketTypes: props.sortid, //分类id
          sessionid: session.value, //场次id
          numberMax: stepperMax.value,
          productName: productName.value, //区分活动预约与共享预约
          timeRangeVos: meetingRoomchecked.value,
        },
      });
    }
  }
};

const timeChangeClick = (key) => {
  if (isDateDisabled(key)) {
    return
  }
  timeKey.value = key;

};

const moreTimeClick = () => {
  showTime.value = true;
};

onMounted(() => {
  if (timeList.value.length > 0) {
    timeChangeClick(timeList.value[0].yearTime);
  }
});
var currentTicketPrice = 0;
const useOpenAndClose = () => {
  const session = ref('');
  const initSession = () => {
    for (let item of props.sessionlist) {
      if (!item.isTimePassed) {
        session.value = item.id;
        break;
      }
    }
  };
  const closeBookPopup = () => {
    if (showTime.value) {
      showTime.value = false;
    } else {
      emit('closePopup');
    }
  };

  const openPopup = () => {
    if (props.sessionlist?.length > 0) {
      props.sessionlist.forEach((item) => {
        item.isTimePassed = isTimePassed(item.endTime);
      });
      stockCount.value = props.sessionlist[0].stockCount;
      initSession();
    }

    props.goodsInfoList.forEach((el) => {
      if (el.id === props.productid) {
        checkCard.value = el.billingMethod;
        currentTicketPrice = el.marketPrice
        // 这里prop应该是永远只有一个小时卡，不然就会可能请求别的小时卡参数
        if (productName.value === '2' && [1, 2].includes(el.billingMethod)) {
          api.getHourPeriod(props.spotId).then((res) => {
            res.data.sort(
                (a, b) => new Date(a.spotDate) - new Date(b.spotDate)
            );
            meetingRoomHourList.value = res.data;
            checkMeetingRoomHourList.value = res.data[0].spotDate;
          });

        }

      }

    });
    ticketTypes.value = props.productid;
    getTicketDetail();
  };

  const moreTimeClick = () => {
    showTime.value = true;
  };

  const closeCalendarClick = () => {
    showTime.value = false;
  };
  return {
    session,
    closeBookPopup,
    openPopup,
    moreTimeClick,
    closeCalendarClick,
    initSession,
  };
};

// 共享预约相关参数
const subscribeVisible = ref(false);
const subscribeCurrentDate = ref([]);
const subscribeCurrentTime = ref([]);
const checkStartTime = ref(false);
const subscribeMinDate = ref(null);

function getSubscribeMaxDate() {
  console.log('subscribeMinDate.value', subscribeMinDate.value)
  var maxd = moment(subscribeMinDate.value).add(2, 'days').toDate()
  console.log('maxd', maxd)
  return maxd;
}

const subscribeMaxDate = ref(null);
// const subscribeMinHour = ref(0);
// const subscribeMinMinutes = ref(0);

const endSubscribeCurrentDate = ref([]);
const endSubscribeCurrentTime = ref([]);
const checkEndTime = ref(false);

// 共享预约开始确认
const onConfirmSubscribe = (opt) => {
  const selectedDateTime = new Date(
      `${opt[0].selectedValues[0]}-${opt[0].selectedValues[1]}-${opt[0].selectedValues[2]}T${opt[1].selectedValues[0]}:${opt[1].selectedValues[1]}`
  );
  const currentDateTime = new Date();
  if (selectedDateTime < currentDateTime) {
    showToast('选择的开始时间不能小于当前时间');
    return;
  }
  if (checkEndTime.value) {
    const endCurrentTime = new Date(
        `${endSubscribeCurrentDate.value[0]}-${endSubscribeCurrentDate.value[1]}-${endSubscribeCurrentDate.value[2]}T${endSubscribeCurrentTime.value[0]}:${endSubscribeCurrentTime.value[1]}`
    );
    const timeDifference = endCurrentTime - selectedDateTime;
    if (timeDifference < 60 * 60 * 1000) {
      showToast('开始时间与结束时间最小要有一小时间隔');
      return;
    }
  }
  // console.log('aaa', `${subscribeCurrentDate.value.join('/')} ${subscribeCurrentTime.value.join(':')}`);
  subscribeCurrentDate.value = opt[0].selectedValues;
  subscribeCurrentTime.value = opt[1].selectedValues;
  // console.log('aaa', `${opt[0].selectedValues.join('/')} ${opt[1].selectedValues.join(':')}`);
  checkStartTime.value = true;
  subscribeVisible.value = false;
};

// 共享预约离开确认
const onCancelfirmSubscribe = () => {
  subscribeVisible.value = false;
  checkStartTime.value = false;
  subscribeCurrentDate.value = [];
  subscribeCurrentTime.value = [];
};

// 共享预约结束时间离开
const endCancelfirmSubscribe = () => {
  endSubscribeVisible.value = false;
  checkEndTime.value = false;
  endSubscribeCurrentDate.value = [];
  endSubscribeCurrentTime.value = [];
};

// 共享预约结束时间确认
const onConfirmEndSubscribe = (opt) => {
  const startCurrentTime = new Date(
      `${subscribeCurrentDate.value[0]}-${subscribeCurrentDate.value[1]}-${subscribeCurrentDate.value[2]}T${subscribeCurrentTime.value[0]}:${subscribeCurrentTime.value[1]}`
  );
  const endCurrentTime = new Date(
      `${opt[0].selectedValues[0]}-${opt[0].selectedValues[1]}-${opt[0].selectedValues[2]}T${opt[1].selectedValues[0]}:${opt[1].selectedValues[1]}`
  );
  if (endCurrentTime < startCurrentTime) {
    showToast('选择的结束时间不能小于开始时间');
    return;
  }
  const endInterval = new Date(
      `${opt[0].selectedValues[0]}-${opt[0].selectedValues[1]}-${opt[0].selectedValues[2]}T${opt[1].selectedValues[0]}:${opt[1].selectedValues[1]}`
  );
  // 计算与当前时间之间的差距
  const timeDifference = endInterval - startCurrentTime;
  if (timeDifference < 60 * 60 * 1000) {
    showToast('最小预约间隔时间为1小时');
    return;
  }
  endSubscribeCurrentDate.value = opt[0].selectedValues;
  endSubscribeCurrentTime.value = opt[1].selectedValues;

  // 调取接口获取金额
  const startTime = `${subscribeCurrentDate.value[0]}-${subscribeCurrentDate.value[1]}-${subscribeCurrentDate.value[2]} ${subscribeCurrentTime.value[0]}:${subscribeCurrentTime.value[1]}:00`;
  const endTime = `${opt[0].selectedValues[0]}-${opt[0].selectedValues[1]}-${opt[0].selectedValues[2]} ${opt[1].selectedValues[0]}:${opt[1].selectedValues[1]}:00`;
  const params = {
    startTime: `${startTime}`,
    endTime: `${endTime}`,
    goodsId: ticketTypes.value,
  };
  api.getWorkHourPrice(params).then((res) => {
    if (res.data) {
      workPrice.value = res.data;
    }
  });

  checkEndTime.value = true;
  endSubscribeVisible.value = false;
};

// 共享预约打开结束时间预约弹窗函数
const openEndtimeModal = () => {
  if (checkStartTime.value) {
    endSubscribeVisible.value = true;
  } else {
    showToast('请先选择开始时间');
  }
};

const endSubscribeVisible = ref(false);

// 共享会议室相关参数
const meetingRoom = ref(false);
const meetingRoomchecked = ref();
const meetingRoomHourList = ref([]);
const checkMeetingRoomHourList = ref('');

// 健身房选择时间参数
const fitnessModalVisible = ref(false);
const fitnessCurrentTime = ref(['00', '00']);
// const fitnessEndTime = ref('结束时间');
// const fitnessStartTime2 = ref('');
const closeFitnessModalClick = (opt) => {
  const currentDate = moment().format('YYYY/MM/DD')
  if (currentDate === timeKey.value) {
    const nowTime = moment().format('HH:MM');
    const checkTime = `${opt.selectedValues[0]}:${opt.selectedValues[1]}`;
    if (checkTime < nowTime) {
      showToast('选择的时间不能小于当前时间')
      return;
    }
  }

  fitnessCurrentTime.value = opt.selectedValues;

  fitnessModalVisible.value = false;
};

const fitnessEndTime = computed(
    () => {
      const s = `${timeKey.value.replaceAll('/', '-')} ${fitnessCurrentTime.value.join(':')}`
      const fitnessStartTime2 = moment(s)
      const end2 = moment(s).add(2,
          'h')
      return (end2.format('YYYY/MM/DD') !== fitnessStartTime2.format('YYYY/MM/DD') ? '次日' : '') + end2.format('HH:mm:ss')

    }
)
// 选择小时
const checkMeetingRoomHour = () => {
  meetingRoom.value = false;
};

// 共享会议室时间处理
const sharedFormatDate = (date) => {
  const year = date?.getFullYear();
  const month = date?.getMonth() + 1; // 月份从0开始，需要加1
  const day = date?.getDate();
  const hours = date?.getHours();

  const formattedDate = `${year}年${month}月${day}日${hours}点`;
  return formattedDate;
};

const workPrice = ref(0);

//获取支付价格
const getPrice = () => {
  if (checkCard.value === 1 && productName.value === '1') {
    return workPrice.value;
  } else if (checkCard.value === 1 && productName.value === '2') {
    if (meetingRoomchecked?.value?.length > 0) {
      return allPrice.value * meetingRoomchecked?.value?.length;
    } else {
      return 0;
    }
  } else {
    return allPrice.value;
  }
};

const {session, closeBookPopup, openPopup, closeCalendarClick} =
    useOpenAndClose();


function isDateDisabled(yearTime) {
  if (!yearTime) {
    return true
  }
  var yt = yearTime.replaceAll('/', '-').trim()
  var ytt = moment(yt).format('YYYY-MM-DD')
  console.log('yt', yt)
  for (let i = 0; i < meetingRoomHourList.value.length; i++) {
    var e = meetingRoomHourList.value[i];
    if (moment(e.spotDate.trim()).format('YYYY-MM-DD') === ytt) {
      for (let j = 0; j < e.timeRangeVoList.length; j++) {
        var ti = e.timeRangeVoList[j];
        console.log('ti', ti)
        if (ti.timeStatue === 2) {
          // timeRange:2023-12-27 02:00:00~03:00:00
          // console.log('ti',ti)

          return true
        }
      }
    }
  }
  return false
  // meetingRoomHourList.filter((e) => {
  //   var datedddd = item.yearTime.replaceAll('/', '-')
  //   console.log('e.spotDate,datedddd', e.spotDate, datedddd)
  //   return e.spotDate === datedddd
  // })[0].timeRangeVoList.filter((t) => t.timeStatue == 1).length
}
</script>

<template>
  <van-popup
      teleport="body"
      class="van_popup"
      :style="{ 'max-height': '70vh' }"
      v-model:show="props.showPopup"
      round
      position="bottom"
      :close-on-click-overlay="false"
      @click-overlay="closeBookPopup"
      @open="openPopup"
  >
    <div
        class="box"
        v-show="
        !showTime &&
        !fitnessModalVisible &&
        !meetingRoom &&
        !subscribeVisible &&
        !endSubscribeVisible
      "
    >
      <div class="header">
        <div class="name">{{ props.title }}</div>
        <img
            @click="closeBookPopup"
            class="close"
            src="@/assets/images/icons/close-666666.png"
            alt=""
        />
      </div>
      <div class="content">
        <div class="content_top">
          <div class="type" v-if="goodsInfoList?.length">
            <div class="name">门票种类</div>
            <div class="button_list">
              <div
                  v-for="item in goodsInfoList"
                  :key="item.id"
                  @click="ticketTypesClick(item)"
                  class="button"
                  :class="{ action_button: ticketTypes === item.id }"
              >
                {{ item.ticketName }}
              </div>
            </div>
          </div>
          <div class="type" v-if="props.sessionlist?.length > 0">
            <div class="name">场次</div>
            <div class="button_list">
              <div
                  v-for="item in props.sessionlist"
                  :key="item.id"
                  @click="sessionClick(item)"
                  class="button"
                  :class="{
                  action_button: session === item.id,
                  button_disabled: item.isTimePassed && isToday,
                }"
              >
                {{ item.beginTime }}-{{ item.endTime }}
              </div>
            </div>
          </div>
          <div
              class="type"
              v-if="
              (productName === '3' && checkCard === 4) ||
              (productName === '2' && checkCard === 2) ||
              (productName === '1' && checkCard === 2)
            "
          >
            <div class="time">
              <!--             天卡 -->
              <div class="name">使用日期</div>
              <div class="time_list">
                <div
                    @click="timeChangeClick(item.yearTime)"
                    v-for="item in timeList"
                    :key="item.yearTime"
                    class="time_button"
                    :class="{ time_button_action: timeKey === item.yearTime,
                   time_button_disabled: isDateDisabled(item.yearTime)
                   }"
                >
                  <div class="top">{{ item.name }}</div>
                  <div class="bottom">{{ item.time }}</div>
                </div>
                <div class="time_button more" @click="moreTimeClick" v-if="!( productName==2 && checkCard == 2 )">
                  <div class="top">更多</div>
                  <div class="bottom">日期</div>
                </div>
              </div>
            </div>
          </div>
          <div class="type" v-if="productName === '2' && checkCard === 1">
            <div class="time">
              <div class="name">使用日期</div>
              <div class="time_list">
                <div
                    class="time_button"
                    v-for="(item, index) in meetingRoomHourList"
                    @click="meetingRoomTimeChangeClick(item.spotDate)"
                    :key="item.spotDate"
                    :class="{
                    time_button_action:
                      item.spotDate === checkMeetingRoomHourList,
                  }"
                >
                  <div class="top">{{ getMeetingRoomDate(index) }}</div>
                  <div class="bottom">{{ item.spotDate.slice(5, 10) }}</div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="productName === '3' && checkCard === 5" class='fintness'>
            购买之日起，半年内有效
          </div>
          <div v-if="productName === '2' && checkCard === 1" class="fitness">
            <div class="fitness-title">使用时段</div>
            <div class="fitness-flex" @click="meetingRoom = true">
              <div v-if="meetingRoomchecked?.length > 0">
                <div v-if="meetingRoomchecked?.length === 1">
                  {{ meetingRoomchecked[0] }}
                </div>
                <div v-else>
                  <div>{{ meetingRoomchecked[0] }}</div>
                  <div>{{ meetingRoomchecked[1] }}</div>
                  <div>等，共{{ meetingRoomchecked.length }}个时间段</div>
                </div>
              </div>
              <div v-else class="fitness-div-flex">
                <div class="subscribe">预约时间</div>
                <div class="start">开始时间</div>
                <div class="line"></div>
                <div class="end">结束时间</div>
              </div>
            </div>
          </div>
          <div
              v-if="
              (productName === '1' && checkCard === 3) ||
              (productName === '3' && checkCard === 6)
            "
              class="fitness"
          >
            <div class="fitness-title">使用时段</div>
            <div class="fitness-flex">
              <div class="subscribe">{{ moment().format('YYYY年MM月DD') }}日</div>
              <div class="line"></div>
              <div class="end">{{ sharedFormatDate(maxDate) }}</div>
            </div>
          </div>
          <div class="fitness" v-if="productName === '3' && checkCard === 4">
            <div class="fitness-title">使用时段</div>
            <div class="fitness-flex">
              <div class="subscribe">预约时间</div>
              <div class="start" @click="fitnessModalVisible = true">
                {{
                  fitnessCurrentTime.length
                      ? fitnessCurrentTime.join(':') + ':00'
                      : '开始时间'
                }}
              </div>
              <div class="line"></div>
              <div class="end">{{ fitnessEndTime }}</div>
            </div>
          </div>

          <div class="fitness" v-if="productName === '1' && checkCard === 1">
            <div class="fitness-title">使用时段</div>
            <div class="fitness-flex">
              <div class="subscribe">预约时间</div>
              <div class="start" @click="subscribeVisible = true">
                {{
                  checkStartTime
                      ? `${subscribeCurrentDate.join(
                          '/'
                      )} ${subscribeCurrentTime.join(':')}`
                      : '开始时间'
                }}
              </div>
              <div class="line"></div>
              <div class="end" @click="openEndtimeModal">
                {{
                  checkEndTime
                      ? `${endSubscribeCurrentDate.join(
                          '/'
                      )} ${endSubscribeCurrentTime.join(':')}`
                      : '结束时间'
                }}
              </div>
            </div>
          </div>
          <div class="number" v-if="productName === '活动预约'">
            <div class="name">购买数量</div>
            <van-stepper
                v-model="number"
                integer
                :max="stepperMax"
                :disabled="!stepperMax"
                @change="numberChange"
                @overlimit="overlimit"
            />
          </div>
        </div>
      </div>
      <div class="popup_bottom">
        <div class="button_box">
          <div
              class="book_button"
              :class="{ book_button_disabled: !stepperMax }"
              @click="bookClick"
          >
            预订
          </div>
          <div class="price">
            <span class="icon">￥</span>
            <span class="price_number">{{ getPrice() }}</span>
          </div>
          <div class="text">应付金额：</div>
        </div>
      </div>
    </div>
    <div class="calendar_box" v-show="fitnessModalVisible">
      <van-time-picker
          v-model="fitnessCurrentTime"
          title="预约开始时间"
          :min-time="moment(timeKey).toDate().getDate()!==moment().toDate().getDate()?'00:00':  moment().add(1,'minutes').format('HH:mm')"
          @cancel="(fitnessModalVisible = false)"
          @confirm="closeFitnessModalClick"
      />
    </div>

    <div class="calendar_box" v-if="subscribeVisible">
      <van-picker-group
          title="预约日期"
          :tabs="['选择日期', '选择时间']"
          @confirm="onConfirmSubscribe"
          @cancel="onCancelfirmSubscribe"
      >
        <van-date-picker
            v-model="subscribeCurrentDate"
            :min-date="subscribeMinDate"
            :max-date="getSubscribeMaxDate()"
        />
        <van-time-picker v-model="subscribeCurrentTime"
                         :min-time="moment(subscribeCurrentDate.join('-')).isAfter(moment())?'00:00': moment().format('HH:mm') "
        />
      </van-picker-group>
    </div>
    <div class="calendar_box" v-if="endSubscribeVisible">
      <van-picker-group
          title="预约结束日期"
          :tabs="['选择日期', '选择时间']"
          @confirm="onConfirmEndSubscribe"
          @cancel="endCancelfirmSubscribe"
      >
        <van-date-picker
            v-model="endSubscribeCurrentDate"
            :min-date="moment(subscribeCurrentDate.join('-')).toDate()||subscribeMinDate"
            :max-date="getSubscribeMaxDate()"
        />
        <van-time-picker v-model="endSubscribeCurrentTime"
                         :min-time="moment(endSubscribeCurrentDate.join('-')).isAfter(moment(subscribeCurrentDate.join('-')))?'00:00':subscribeCurrentTime.join(':')"
        />
      </van-picker-group>
    </div>
    <div class="calendar_box" v-show="showTime">
      <div class="header">
        <div class="name">使用日期</div>
        <img
            @click="closeCalendarClick"
            class="close"
            src="@/assets/images/icons/close-666666.png"
            alt=""
        />
      </div>
      <van-calendar
          v-if="!loading"
          v-show="showTime"
          :default-date="timeKeyDate"
          :show-title="false"
          :show-subtitle="false"
          :poppable="false"
          :show-confirm="false"
          :style="{ maxHeight: 'calc(70vh - 6.3rem)' }"
          :min-date="minDate"
          :max-date="maxDate"
          row-height="3rem"
          @select="selectChange"
      />
    </div>
    <div class="calendar_box" v-show="meetingRoom">
      <div class="header">
        <div class="name">选择预约时间</div>
        <img
            @click="(meetingRoom = false), (meetingRoomchecked = [])"
            class="close"
            src="@/assets/images/icons/close-666666.png"
            alt=""
        />
      </div>
      <div class="calendar_box_radio">
        <van-checkbox-group v-model="meetingRoomchecked" class="radio-group">
          <div v-for="(item, index) in meetingRoomHourList" :key="index">
            <div v-if="item.spotDate === checkMeetingRoomHourList">
              <div v-for="el in item.timeRangeVoList" :key="el.timeRange">
                <van-checkbox
                    class="radio"
                    :disabled="el.timeStatue !== 0"
                    :name="el.timeRange"
                >{{ el.timeRange }}
                </van-checkbox
                >
              </div>
            </div>
          </div>
        </van-checkbox-group>
        <van-button
            type="primary"
            class="mettingRoom-corfim"
            @click="checkMeetingRoomHour"
        >确定
        </van-button
        >
      </div>
    </div>
  </van-popup>
</template>

<style scoped lang="scss">
:deep(.van-skeleton) {
  padding: 0;
}

:deep(.van-skeleton-paragraph) {
  width: 6.5rem;
  height: 5.1rem;
}

:deep(.van-skeleton-paragraph:not(:first-child)) {
  margin-top: 0;
}

@mixin header {
  height: 2.8rem;
  margin-top: 2rem;
  justify-content: space-between;
  display: flex;
  margin-bottom: 1.5rem;

  .name {
    font-size: 2rem;
    font-weight: bold;
    color: #2f3836;
  }

  .close {
    width: 1.6rem;
    height: 1.6rem;
  }
}

.box {
  padding: 0 2rem;
  display: flex;
  flex-direction: column;

  .header {
    @include header;
  }

  .content {
    max-height: calc(70vh - 2rem - 2.8rem - 1.5rem - 9rem);
    display: flex;
    flex-direction: column;
    overflow-y: auto;

    .content_top {
      padding-top: 0.5rem;
      flex: 1;
    }
  }

  .popup_bottom {
    height: 9rem;

    .button_box {
      padding-top: 1rem;
      display: flex;
      flex-direction: row-reverse;
      align-items: center;

      .book_button {
        height: 3.8rem;
        line-height: 3.8rem;
        background: var(--van-primary-color);
        border-radius: 0.5rem;
        font-size: 1.6rem;
        color: #ffffff;
        padding: 0 3rem;
        margin-left: 1rem;
      }

      .book_button:active {
        background: #4b947f;
      }

      .book_button_disabled {
        opacity: 0.5;
      }

      .price {
        color: #ed6316;
        overflow: hidden;

        .icon {
          font-size: 1.4rem;
        }

        .price_number {
          font-size: 2.2rem;
        }
      }

      .text {
        font-size: 1.4rem;
        color: #999999;
      }
    }
  }

  .type {
    margin-bottom: 2rem;

    .name {
      font-size: 1.4rem;
      color: #999999;
      line-height: 1.6rem;
      margin-bottom: 1rem;
    }

    .button_list {
      display: flex;
      flex-wrap: wrap;

      .button {
        height: 3rem;
        background: rgba(0, 0, 0, 0.05);
        border-radius: 0.5rem;
        font-size: 1.4rem;
        color: #666666;
        line-height: 3rem;
        text-align: center;
        padding: 0 1.5rem;
        margin-right: 1rem;
        margin-bottom: 1.5rem;
      }

      .action_button {
        color: #ffffff;
        background: var(--van-primary-color);
      }

      .button_disabled {
        opacity: 0.5;
      }
    }
  }

  .time {
    .name {
      font-size: 1.4rem;
      color: #999999;
      line-height: 1.6rem;
      margin-bottom: 1rem;
    }

    .time_list {
      display: flex;
      padding-bottom: 2rem;
      border-bottom: 0.1rem solid #eeeeee;

      .time_button {
        width: 6.5rem;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        text-align: center;
        height: 5.1rem;
        background: rgba(0, 0, 0, 0.05);
        border-radius: 0.5rem;
        font-size: 1.2rem;
        color: #666666;
        margin-right: 1rem;

        .top {
          margin-bottom: 0.3rem;
        }

        .button {
          margin-top: 0.3rem;
        }
      }

      .time_button_action {
        background-color: Var(--van-primary-color);
        color: #ffffff;
      }

      .time_button_disabled {
        opacity: 0.5;
      }

      .time_button_disabled {
        color: #bbbbbb;
      }

      .more {
        color: var(--van-primary-color);
        width: 5.4rem;
      }

      .time_none {
        width: 100%;
        height: 5.1rem;
        line-height: 5.1rem;
        text-align: center;
        font-size: 1.4rem;
        color: #666666;
      }
    }
  }

  .fitness {
    margin-top: -1.5rem;
    margin-bottom: 2rem;

    .fitness-title {
      color: #999999;
      font-size: 1.4rem;
    }

    .fitness-flex {
      margin-top: 1rem;
      display: flex;
      justify-content: space-around;
      align-items: center;
      font-size: 1.4rem;

      .fitness-div-flex {
        margin-top: 1rem;
        width: 100%;
        display: flex;
        justify-content: space-around;
        align-items: center;
        font-size: 1.4rem;
      }

      .line {
        width: 5rem;
        border: 1px solid #999999;
      }
    }
  }

  .number {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 2rem;
    margin-bottom: 4rem;

    .name {
      font-size: 1.4rem;
      color: #999999;
    }
  }
}

.calendar_box {
  .header {
    @include header;
    padding: 0 2rem;
  }

  .calendar_box_radio {
    padding: 2rem;

    .radio-group {
      .radio {
        margin-top: 1rem;
        font-size: 1rem;
      }
    }

    .mettingRoom-corfim {
      margin-top: 2rem;
    }
  }
}
</style>
